package org.dreamwork.jasmine2.sample.ajax;

import org.dreamwork.jasmine2.ajax.RequestMethod;
import org.dreamwork.jasmine2.annotation.AjaxMethod;
import org.dreamwork.jasmine2.annotation.AjaxParameter;
import org.dreamwork.jasmine2.annotation.AjaxService;
import org.dreamwork.jasmine2.engine.HttpContext;
import sample.data.Category;
import sample.data.Person;

import javax.servlet.ServletContext;
import java.io.*;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-4-27
 * Time: 下午2:59
 */
@AjaxService ("otherAjax")
public class OtherAjax {
    @AjaxMethod (contentType = "image/png", method = RequestMethod.POST)
    public byte[] getImage (@AjaxParameter (name = "src") String src) throws IOException {
        HttpContext context = HttpContext.current ();
        ServletContext application = context.getApplication ();
        String folder = application.getRealPath ("/images/");
        File file = new File (folder, src);
        if (!file.exists ()) return null;

        InputStream in = new FileInputStream (file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream (1024);
        byte[] buff = new byte[1024];
        int length;

        try {
            while ((length = in.read (buff)) != -1)
                baos.write (buff, 0, length);
        } finally {
            in.close ();
        }
        return baos.toByteArray ();
    }

    @AjaxMethod (method = RequestMethod.POST)
    public Category getCategory (
            @AjaxParameter (name="date", serialize = true)Date date,
            @AjaxParameter (name="who", serialize = true)Person who) {
        System.out.println (who);
        System.out.println (date);

        Category c = new Category ();
        c.setId (1);
        c.setName ("category 1");
        return c;
    }
}
